package com.zhaotianhao.serviceorder.controller;


import cn.hutool.http.HttpStatus;
import cn.hutool.jwt.JWT;
import com.zhaotianhao.serviceorder.common.JsonResult;
import com.zhaotianhao.serviceorder.common.WebUtils;
import com.zhaotianhao.serviceorder.dto.OrderDto;
import com.zhaotianhao.serviceorder.entity.Order;
import com.zhaotianhao.serviceorder.service.IOrderService;
import com.zhaotianhao.serviceorder.vo.CartVo;
import com.zhaotianhao.serviceorder.vo.SkuVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Z-7
 * @since 2022-04-30
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private IOrderService iOrderService;

    @PostMapping("/createOrder")
    public JsonResult createOrder(@RequestBody OrderDto orderDto) {
        String token = WebUtils.getRequest().getHeader("token");
        JWT jwt = JWT.of(token).setKey("zhao".getBytes());
        long userId = Long.parseLong(jwt.getPayload("userId") + "");
        String username = (String) jwt.getPayload("username");

        // 获取所有选中的订单
        List<SkuVo> skuVos =  iOrderService.getSelectSku(orderDto.getSkuIds(),userId);
        // 校验库存
        Integer result = iOrderService.checkoutRepertory(skuVos);
        if (result != null) {
            return JsonResult.faild(skuVos.get(result).getTitle()+"商品库存不足,下单失败!");
        }
        log.info("库存充足");
        // 修改库存
        Boolean stock = iOrderService.updateStock(skuVos);
        log.info("库存预扣完成");

        // 订单主表 详情表 状态
        String orderId = iOrderService.createOrder(skuVos,userId,username);

        // 清除购物车
        Boolean flag = iOrderService.clearCart(userId,skuVos);
        log.info("购物车已清理");

        // 生成一个cartVo
        CartVo cartVo = iOrderService.createCartVo(userId,skuVos);
        return JsonResult.successd(orderId);
    }

    @GetMapping("getOrderById")
    public JsonResult getOrderById(OrderDto orderDto) {
        return iOrderService.getOrderById(orderDto);
    }

    @PostMapping("payment")
    public JsonResult payment(@RequestBody OrderDto orderDTO) {
        Order order = iOrderService.getById(orderDTO.getOrderId());
        BeanUtils.copyProperties(orderDTO,order);
        boolean updateOrder = iOrderService.updateById(order);
        if(updateOrder){
            return JsonResult.successd("结算成功");
        }
        return JsonResult.faild(HttpStatus.HTTP_INTERNAL_ERROR,"结算失败");
    }
}
